package club.janna.concurrency.example.sync;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * synchronized 实例
 * @Auther: guopanbo
 * @Date: 2018/7/22 15:16
 * @Description:
 */
@Slf4j
public class SynchronizedExample2 {

    /**
     * synchronized 类
     * @param j
     */
    public static void test1(int j) {
        synchronized (SynchronizedExample2.class) {
            for(int i = 0;i < 10;i ++) {
                log.info("test1 - {} - {}", j, i);
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * synchronized 静态方法
     * @param j
     */
    public static synchronized void test2(int j) {
        for(int i = 0; i < 10;i ++) {
            log.info("test2 - {} - {}", j, i);
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        SynchronizedExample2 example1 = new SynchronizedExample2();
        SynchronizedExample2 example2 = new SynchronizedExample2();
        ExecutorService service = Executors.newCachedThreadPool();
        service.execute(() -> {
            example1.test1(1);
        });
        service.execute(() -> {
            example2.test2(2);
        });
        service.shutdown();
    }
}
